<template>
	<div class="page" v-loading="loading">
		<div class="page-item">
			<div class="title">人员名称</div>
			<el-scrollbar view-class="list">
				<ele-loading :style="{ flex: 1, paddingRight: '16px', overflow: 'auto' }">
					<el-tree ref="treeRef" accordion :props="{ label: 'name', children: 'child', isLeaf: 'leaf' }" :load="loadNode" lazy highlight-current node-key="id" :style="{ '--ele-tree-item-height': '34px' }" @node-click="handleNodeClick">
						<template #default="scope">
							<el-icon style="margin-right: 6px; color: #ffd659; font-size: 16px">
								<svg v-if="!scope.data?.leaf" data-v-730513b0="" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="4" stroke-linejoin="round" style="fill: currentcolor"><path d="M3 6H16L25 14H45V42H3Z"></path></svg>
								<svg v-else data-v-730513b0="" viewBox="0 0 48 48" fill="none" stroke="currentColor" stroke-width="3.5" stroke-linejoin="round" style="transform: scale(0.9) translateY(1px); color: #faad14">
									<path d="M28 2V16H41M28 2H7V45H41V16Z"></path>
									<path d="M15 14H22"></path>
									<path d="M15 25H33"></path>
									<path d="M15 35H33"></path>
								</svg>
							</el-icon>
							<span class="el-tree-node__label" style="margin-top: 2px">
								{{ scope.data.name ? scope.data.name : scope.data.nickname }}
							</span>
						</template>
					</el-tree>
				</ele-loading>
			</el-scrollbar>
		</div>
		<div class="page-item">
			<div class="title">物品名称</div>
			<div class="box">
				<div class="box-item">
					<el-table ref="tableRef" :data="tableData" @selection-change="handleSelectionChange" v-model:selection="selections" row-key="id">
						<el-table-column type="selection" :selectable="selectable" width="55" :reserve-selection="true" />
						<el-table-column label="一级大类" prop="cate_father.title" show-overflow-tooltip></el-table-column>
						<el-table-column label="二级大类" prop="cate.title" show-overflow-tooltip></el-table-column>
						<el-table-column label="产品名称" prop="title" show-overflow-tooltip></el-table-column>
						<el-table-column label="产品编码" prop="code" show-overflow-tooltip></el-table-column>
					</el-table>
					<div style="display: flex; align-items: center; justify-content: center; margin-top: 20px">
						<el-pagination v-model:current-page="pages.page" v-model:page-size="pages.limit" :page-sizes="[10, 20, 30, 40]" :background="background" layout="total, sizes, prev, pager, next" :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
					</div>
				</div>
			</div>
		</div>
		<div class="box-footer">
			<el-button class="btn" size="large" @click="router.go(-1)">取消</el-button>
			<el-button class="btn" size="large" type="primary" @click.prevent.stop="onSubmit">保存</el-button>
		</div>
	</div>
</template>

<script setup>
	import { nextTick, ref, onMounted } from 'vue';
	import { useUserStore } from '@/store/user/index.js';
	import { useRoute, useRouter } from 'vue-router';
	import { getDepartmentTree, getDepartAdminsList, getDepartProductsList, getDepartProductsListByDepartmentId, add_goods_admin, admin_goods } from '@/api/PersonnelBindingItems/index';
	import { ElMessage } from 'element-plus';
	const userStore = useUserStore();
	const route = useRoute();
	const router = useRouter();

	//部门树列表
	const supplierList = ref([]);

	// 树形控件
	const treeRef = ref(null);

	//选择的人员
	const personnel_id = ref('');

	// loading
	const loading = ref(false);

	//表格数据
	const tableData = ref([]);

	//总条数
	const total = ref(0);

	//分页条件
	const pages = ref({ page: 1, limit: 10 });

	// 多选选中数据
	const selections = ref([]);

	// tableRef
	const tableRef = ref(null);

	//获取物品数据
	const getList = async () => {
		//如果没有部门 则查所有物品
		if (!userStore.departmentId) {
			let Departres = await getDepartProductsList({
				page: pages.value.page,
				pagesize: pages.value.limit
			});
			if (Departres.data.length != 0) {
				tableData.value = Departres.data.data;
				total.value = Departres.data.total;
			}
		}

		//如果有部门 则查部门下的物品
		if (userStore.departmentId) {
			getDepartProductsListByDepartmentIdList(userStore.departmentId);
		}
	};

	//根据部门id获取物品数据
	const getDepartProductsListByDepartmentIdList = async (id) => {
		let Departres = await getDepartProductsListByDepartmentId({
			department_id: id,
			page: pages.value.page,
			pagesize: pages.value.limit
		});
		if (Departres.data.length != 0) {
			tableData.value = Departres.data.data;
			total.value = Departres.data.total;
		} else {
			tableData.value = [];
			total.value = 0;
		}
	};

	//多选
	let warningShown = false;
	const handleSelectionChange = (val) => {
		if (!personnel_id.value) {
			if (!warningShown) {
				ElMessage.warning('请选择员工');
				warningShown = true;
			}
			tableRef.value.clearSelection();
			return;
		}

		selections.value = val;
	};

	// 分页点击条数
	const handleSizeChange = (val) => {
		pages.value.limit = val;
		getList();
	};
	// 分页点击页数
	const handleCurrentChange = (val) => {
		pages.value.page = val;
		getList();
	};

	//是否是单个部门
	const isD = ref(false);

	//部门懒加载
	const loadNode = async (node, resolve) => {
		if (node.level === 0) {
			loading.value = true;
			//查部门树
			let res = await getDepartmentTree({ admin_id: userStore.admin_id });
			loading.value = false;
			//如果有length 说明查的是全部部门
			if (res.data.length) {
				//全部部门
				isD.value = false;
				//存储数据
				supplierList.value = res.data;
				//返回数据到树组件渲染
				return resolve(
					res.data.map((item) => {
						return {
							...item,
							leaf: false
						};
					})
				);
			} else {
				//单个部门
				isD.value = true;
				//返回数据到树组件渲染
				return resolve([res.data]);
			}
		}
		if (node.level === 1) {
			//判断是否是单个部门
			if (isD.value) {
				loading.value = true;
				//查单个部门下面的人员
				let res = await getDepartAdminsList({ depart_id: node.data.id });
				loading.value = false;
				return resolve(
					res.data.map((item) => {
						return {
							...item,
							leaf: true
						};
					})
				);
			}

			//返回对应的 组数据
			if (node.data.child.length) {
				return resolve(
					node.data.child.map((item) => {
						return {
							...item,
							leaf: false
						};
					})
				);
			}
			//查单个部门下面的人员
			let res = await getDepartAdminsList({ depart_id: node.data.id });
			loading.value = false;
			return resolve(
				res.data.map((item) => {
					return {
						...item,
						leaf: true
					};
				})
			);
		}
		if ((node.level = 2)) {
			loading.value = true;
			//查单个部门下面的人员
			let res = await getDepartAdminsList({ depart_id: node.data.id });
			loading.value = false;
			return resolve(
				res.data.map((item) => {
					return {
						...item,
						leaf: true
					};
				})
			);
		}
	};

	// 树组件点击事件
	const handleNodeClick = async (node, treenode) => {
		if (treenode.level == 1) {
			//多部门
			if (!isD.value) {
				//根据部门id获取物品数据
				getDepartProductsListByDepartmentIdList(node.id);
				//清空勾选
				nextTick(() => {
					tableRef.value.clearSelection();
				});
				//清空人
				personnel_id.value = '';
				//保存部门id
				userStore.departmentId = node.id;
			}
		}
		if (treenode.level == 2) {
			//单部门
			if (isD.value) {
				//保存员工id
				personnel_id.value = node.id;
				//清空勾选
				nextTick(() => {
					tableRef.value.clearSelection();
				});

				//根据员工id获取物品 回显勾选
				const res = await admin_goods({ admin_id: personnel_id.value });
				if (res?.data) {
					selections.value = res.data.map((item) => item);
					//设置表格数据为勾选
					selections.value.forEach((item) => {
						tableRef.value.toggleRowSelection(item, true);
					});
				}
				//重置page
				pages.value.page = 1;
				getList();
			}

			//多部门
			if (!isD.value) {
				//有组
				if (!treenode.data.leaf) {
					//根据部门id获取物品数据
					getDepartProductsListByDepartmentIdList(node.id);
					//清空勾选
					nextTick(() => {
						tableRef.value.clearSelection();
					});
					//清空人
					personnel_id.value = '';
					//保存部门id
					userStore.departmentId = node.id;
				}
				//无组
				if (treenode.data.leaf) {
					//保存员工id
					personnel_id.value = node.id;
					//清空勾选
					nextTick(() => {
						tableRef.value.clearSelection();
					});

					//根据员工id获取物品 回显勾选
					const res = await admin_goods({ admin_id: personnel_id.value });
					if (res?.data) {
						selections.value = res.data.map((item) => item);
						//设置表格数据为勾选
						selections.value.forEach((item) => {
							tableRef.value.toggleRowSelection(item, true);
						});
					}
					//重置page
					pages.value.page = 1;
					getList();
				}
			}
		}
		if (treenode.level == 3) {
			//保存员工id
			personnel_id.value = node.id;
			//清空勾选
			nextTick(() => {
				tableRef.value.clearSelection();
			});

			//根据员工id获取物品 回显勾选
			const res = await admin_goods({ admin_id: personnel_id.value });
			if (res?.data) {
				selections.value = res.data.map((item) => item);
				//设置表格数据为勾选
				selections.value.forEach((item) => {
					tableRef.value.toggleRowSelection(item, true);
				});
			}
			//重置page
			pages.value.page = 1;
			getList();
		}
	};

	// 提交表单
	const onSubmit = async () => {
		if (!personnel_id.value) return ElMessage.warning('请选择员工');
		if (selections.value.length == 0) return ElMessage.warning('请选择物品');
		try {
			const res = await add_goods_admin({ goods_id: selections.value.map((item) => item.id).join(','), admin_id: personnel_id.value });
			if (res) {
				ElMessage.success(res.msg);
			}
		} catch (error) {
			ElMessage.error(error.message);
		}
	};

	onMounted(async () => {
		await userStore.getDepartmentId();
		// 获取物品数据
		await getList();
	});
</script>

<style lang="scss" scoped>
	:deep(.el-tree-node__label) {
		display: flex;
		justify-content: space-between;
		align-items: center;

		.title {
			font-size: 14px;
		}

		.action {
			display: flex;
			align-items: center;
			gap: 10px;
		}
	}
	.page {
		height: 100%;
		min-height: 100vh;
		background-color: white;
		display: grid;
		grid-template-columns: auto 1fr;
		grid-gap: 20px;
		padding: 20px;
		box-sizing: border-box;

		&-item {
			display: flex;
			flex-direction: column;
			gap: 10px;
			overflow: hidden;

			&:nth-child(1) {
				width: 350px;
			}
		}
	}

	.title {
		font-size: 18px;
		font-weight: bold;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	:deep(.list) {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 10px;
		padding-right: 20px;
		padding-bottom: 20px;

		.list-item {
			padding: 10px;
			cursor: pointer;
			border-radius: 10px;
			background-color: rgb(252, 252, 252);
		}
	}

	:deep(.form) {
		padding-right: 20px;
		padding-bottom: 20px;

		.qualityAgreement .el-form-item__label {
			line-height: 20px;
		}
	}

	/* 自定义样式 */
	.demo-tabs.ele-tabs :deep(.el-tabs__header) {
		--ele-tab-padding: 0;
		--ele-tab-height: 46px;
		--ele-tab-font-size: 16px;
		--ele-tab-simple-hover-color: var(--el-color-primary);
		--ele-tab-simple-hover-bg: none;
		--ele-tab-simple-active-bg: none;
		--ele-tab-simple-active-weight: normal;

		border: none;

		.el-tabs__item {
			& + .el-tabs__item {
				margin-left: 35px;
			}
		}
	}

	.box {
		flex: 1;
		display: flex;
		flex-direction: column;
		gap: 20px;

		&-item {
			flex: 1;
		}

		&-footer {
			grid-column: span 2;
			display: flex;
			justify-content: center;
			align-items: flex-end;
			margin-bottom: 30px;

			.btn {
				width: 150px;
			}
		}
	}
	:deep(.el-table .el-table__header th) {
		background-color: #f5f7fa !important; /* 设置表头背景色 */
	}
</style>
